<?php
!defined('IN_SYSTEM') && exit('Access Denied!');
class UploadModule
{
	function index(){
		global $_G;
		$t=getGP('t','G','int');
		echo $this->html('',$t);exit;
	}
	
	function upload(){
		global $_G;
		$type=getGP('t','P','int');
		if( !$_G['usergroup']['access']['upfile'] && !ISADMIN ) {
			echo $this->html('<ul><li>没有权限</li></ul>',$type);exit;
		}
		include libfile("upload.php");
		$allow_type=$_G['usergroup']['access']['upfiletype']?$_G['usergroup']['access']['upfiletype']:$_G['settings']['upload']['allow_type'];
		$file_size=$_G['usergroup']['access']['upfilesize']?$_G['usergroup']['access']['upfilesize']:$_G['settings']['upload']['file_size'];
		if( $_G['usergroup']['access']['upfiletotal'] > 0 && !ISADMIN ) {
			$total = $_G['db']->result("SELECT SUM(filesize) AS total FROM".table('files')."WHERE uid=".$_G['uid']) ;
			$filetotal=$_G['usergroup']['access']['upfiletotal'] * 1024 - $total;
			if($filetotal <=0 ){
				echo $this->html('<ul><li>没有限额</li></ul>',$type);exit;
			}
		}
		$upload = new upload($allow_type, $file_size, 'upfile',null,$filetotal);
		$upload->set_dir(BASE_ROOT.DATA_DIR.'files/', $_G['settings']['upload']['dir_rule']);
	
		if ( get_config('watermark','upload') ) {
			if(get_config('watermark_image','upload')) {
				$upload->set_watermark(BASE_ROOT.'./static/images/'.get_config('watermark_image','upload'), intval(get_config('watermark_pos','upload')), intval(get_config('watermark_trans','upload')));
			}else{
				$water_text = get_config('watermark_text','upload');
				if(!$water_text) $water_text = $_G['settings']['siteurl'];
				$upload->set_watermark($water_text, intval(get_config('watermark_pos','upload')), intval(get_config('watermark_trans','upload')));
			}
		}
		if ( get_config('auto_resize','upload') ) {
			$upload->set_resize(intval(get_config('resize_width','upload')), intval(get_config('resize_height','upload')));
		}
		if ( get_config('create_thumb','upload') ) {
			$upload->set_thumb(intval(get_config('thumb_width','upload')), intval(get_config('thumb_height','upload')));
		}
		
		$files = $upload->execute();
		if (empty($files)) { 
			$output ='<a href="index.php?m=upload">请选择要上传的文件</a>';
		} else {
			$output = '';
			$idarr = array();
			if(get_config('ftp','upload')){
				include libfile('ftp.php');
				$ftp = new Ftp();
				$conf = array(
					'hostname' => get_config('host','upload'),
					'username' => get_config('username','upload'),
					'password' => get_config('password','upload'),
					'port' => get_config('port','upload'),
					'passive' => get_config('pasv','upload'),
					'debug'	=> true,
				);
				$ftp->connect($conf);
			}
			foreach ($files as $file) {
				if ($file['status'] == 1) {
					$data = array();
					$data['uid'] = $_G['uid'];
					$data['username'] = $_G['username'];
					$data['originalname'] = $file['ogname'];
					$filepath = $file['path'].$file['name'];
					$data['filepath'] = str_replace(DATA_DIR.'files/','', $filepath);
					$data['filesize'] = $file['size'];
					$data['filetype'] = $file['type'];
					$data['fileext'] = $file['ext'];
					$data['type'] = $type;
					$data['dateline'] = TIMESTAMP;
					//缩略图
					if ( get_config('create_thumb','upload') && stristr($file['type'],'image') ) {
						$thumb = $file['path'].'thumb_'.$file['name'];
						if ( file_exists(BASE_ROOT.$thumb) ) {
							$data['thumb'] = str_replace(DATA_DIR.'files/','', $thumb);
						}
						if($_G['settings']['upload']['ftp']){
							$ftp->upload(BASE_ROOT.$thumb,$_G['settings']['upload']['attachdir'].'/'.$data['thumb']);
							@unlink(BASE_ROOT.$thumb);
						}	
					}
					if($_G['settings']['upload']['ftp']) {
						if($ftp->upload(BASE_ROOT.$filepath,$_G['settings']['upload']['attachdir'].'/'.$data['filepath'])){
							@unlink(BASE_ROOT.$filepath);
						}
					}
					$fileid = $_G['db']->insert('files',$data);
					$idarr[] = $fileid;	//放进数组
					if ( stristr($file['type'],'image') ) {
						$ubb = '[img]'.$data['filepath'].'[/img]';
						$ubb2 = '[img][upload='.$fileid.'][/img]';
						$ubb3 = '<img src='.DATA_DIR.'files/'.$data['filepath'].'>';
					} else {
						$ubb = '[file]'.$data['filepath'].'[/file]';
						$ubb2 = '[file][upload='.$fileid.'][/file]';
						$ubb3=null;
					}
					$output .= '<li id="tr_'.$fileid.'"><a href="javascript:;" onclick="to_front(\''.$fileid.'\')" title="设为封面">[设为封面]</a> <a href="javascript:;" onclick="to_editor(\''.$ubb.'\')" title="显示附件路径">[插入]</a> ';
					$output .=$ubb3?'<a href="javascript:;" onclick="to_editor(\''.$ubb3.'\')" title="可见图片">[可视化插入]</a>':'';
					$output .= $data['originalname'].' --- <span style="color:green;cursor:pointer;" onclick="deletefile('.$fileid.')">删除</span></li>';
				} elseif ($file['status'] == -1) {
					$output .= '<li>'.$file['ogname'].' --- <span style="color:red">失败，文件类型不允许。</span></li>';
				} elseif ($file['status'] == -2) {
					$output .= '<li>'.$file['ogname'].' --- <span style="color:red">失败，文件大小超出'.$_G['settings']['upload']['file_size'].'K。</span></li>';
				}elseif ($file['status'] == -3) {
					$output .= '<li>'.$file['ogname'].' --- <span style="color:red">失败，超出允许上传的限额。</span></li>';
				}
			}
			if(get_config('ftp','upload')){
				$ftp->close();
			}
			//临时存放到cookie，发布时更新referid
			$idstr = getGP('admin_upload_attachments','c');
			if ( !empty($idstr) && preg_match('/^([0-9]+(,[0-9])?)+$/', $idstr) ) {
				$exattachments = $_G['db']->fetch_all("SELECT fid,originalname,filepath,thumb,filesize,filetype,fileext,dateline FROM ".DB_PREFIX."files WHERE  fid IN ($idstr)");
				if(!empty($exattachments)){
					foreach($exattachments as  $v){
						if ( stristr($v['filetype'],'image') ) {
							$ubb = '[img]'.$v['filepath'].'[/img]';
							$ubb2 = '[img][upload='.$v['fid'].'][/img]';
							$ubb3 = '<img src='.DATA_DIR.'files/'.$v['filepath'].'>';
						} else {
							$ubb = '[file]'.$v['filepath'].'[/file]';
							$ubb2 = '[file][upload='.$v['fid'].'][/file]';
							$ubb3=null;
						}
						$output .= '<li id="tr_'.$v['fid'].'"><a href="javascript:;" onclick="to_front(\''.$v['fid'].'\')" title="设为封面">[设为封面]</a> <a href="javascript:;" onclick="to_editor(\''.$ubb.'\')" title="显示附件路径">[插入]</a> ';
						$output .=$ubb3?'<a href="javascript:;" onclick="to_editor(\''.$ubb3.'\')" title="可见图片">[可视化插入]</a>':'';
						$output .= $v['originalname'].' --- <span style="color:green;cursor:pointer;" onclick="deletefile('.$v['fid'].')">删除</span></li>';
					}
				}
			}
			
			$idstr = preg_match('/^([0-9]+(,[0-9])?)+$/', trim($idstr)) ? trim($idstr) : '';
			!empty($idstr) && $idstr .= ',';
			$idstr .= implode(',', $idarr);
			set_cookie('admin_upload_attachments', $idstr,36000);
			$output = '<ul>'.$output.'</ul>';
			
			
		}
		echo $this->html($output,$type);exit;
	}
	function delete(){
		global $_G;
		$data['s']=false;
		$id = getGP('id','G','int');
		if($_G['uid']<1 || $id<1){json($data);}
		if(!ican('deleteallfiles')) $where=" AND uid=".$_G['uid'];
		$file = $_G['db']->fetch_one_array("SELECT filepath,thumb FROM".table('files')." WHERE fid=".$id.$whre);
		if(empty($file)){json($data);}
		if($_G['settings']['upload']['ftp']) {
			include libfile('ftp.php');
			$ftp = new Ftp();
			$conf = array(
				'hostname' => get_config('host','upload'),
				'username' => get_config('username','upload'),
				'password' => get_config('password','upload'),
				'port' => get_config('port','upload'),
				'passive' => get_config('pasv','upload'),
				'debug'	=> true,
			);
			$ftp->connect($conf);
			$ftp->delete_file($_G['settings']['upload']['attachdir'].'/'.$file['filepath']);
			if ( !empty($file['thumb']) ) {
				$ftp->delete_file($_G['settings']['upload']['attachdir'].'/'.$file['thumb']);
			}
		}else{
			@unlink(BASE_ROOT.DATA_DIR.'files/'.$file['filepath']);
			if ( !empty($file['thumb']) ) {
				@unlink(BASE_ROOT.DATA_DIR.'files/'.$file['thumb']);
			}
		}
		//cookie delete
		$idstr = getGP('admin_upload_attachments','c');
		if ( !empty($idstr) && preg_match('/^([0-9]+(,[0-9])?)+$/', $idstr) ) {
			$ids=explode(',', $idstr);
			if(is_array($ids))$s=array_diff($ids,array($id));
			if(!empty($s)){
				$idstr .= implode(',', $s);
				set_cookie('admin_upload_attachments', $idstr,36000);
			}else{
				set_cookie('admin_upload_attachments');
			}
		}
			
		$data['s']=true;
		if($_G['settings']['upload']['ftp']){
			$ftp->close();
		}
		$_G['db']->query("DELETE FROM".table('files')."WHERE fid=".$id.$where);
		json($data);
	}
	function html($output='',$t=0){
		$url=url('index.php?m=upload&f=upload');
		$s=<<<EOF
		<html>
	<head>
		<title>附件上传</title>
		<style type="text/css">
			body ,body td {margin:0;padding:0;font-size:12px;font-family:'Verdana','宋体';overflow:hidden;}
			form{margin:0;padding:0;}
			a {color:#2366A8;text-decoration:none;}
			a:hover {color:red;text-decoration:none;}
			input {padding:3px;font-size:12px;margin-right:2px;width:300px;}
			.button ,.button:hover {background:#2782D6;border:1px solid;border-color:#ddd #264F6E #264F6E #ddd;color:#fff;height:25px;width:80px;font-size:12px;}
			ul ,li {margin:0;padding:5px 0;list-style:none;}
		</style>
		<script type="text/javascript" src="admin/script/jquery.js"></script>
		<script type="text/javascript">
		var COOKIE_PRE='{COOKIE_PRE}';
		var COOKIE_DOMAIN='{COOKIE_DOMAIN}';
		var COOKIE_PATH='{COOKIE_PATH}';
		</script>
		<script language="javascript">
		function to_editor(content){
			parent.editor.insertHtml(content);
			//parent.K.plugin["image"].insert(id,content);
		}
		function to_front(id){
			parent.document.getElementById('default_image').value=id;
			alert('成功设为封面，需要保存后才能看到封面效果');
		}
		function addrow(){
			var table=document.getElementById('fuprow');
			var newRow=table.insertRow();
			newRow.insertCell().innerHTML='<input type="file" name="upfile[]" size="30"/><a onclick="cutrow(this);return false;" href="javascript:;">[-]</a>';
			parheight();
		}
		function cutrow(obj){
			var i=obj.parentNode.parentNode.rowIndex;
			var h=document.body.scrollHeight;
			var suh=obj.parentNode.parentNode.offsetHeight;
			document.getElementById('fuprow').deleteRow(i);
			var hh=(parseInt(h)-parseInt(suh));
			parent.document.getElementById('uploadframe').style.height=hh+"px";
		}
		function parheight(){
			var h=document.body.scrollHeight;
			parent.document.getElementById('uploadframe').style.height=h+"px";
		}
		function deletefile(id,obj){
			if(!confirm('确定删除？')) return false;
			if(id){
				$.getJSON('index.php?m=upload&f=delete&id='+id+'&tm='+Math.random(),'',function(data){
					if(data.s==true){
						$('#tr_'+id).remove();
					}else{
					}
				});
			}
		}
		</script>
	</head>
	<body>
	{$output}
	<form name="upload" method="post" action="{$url}" enctype="multipart/form-data">
		<input type="hidden" name="f" value="upload" />
		<input type="hidden" name="t" value="{$t}"/>
		
		<table  id="fuprow" style="float:left;">
			<tr><td><input type="file" name="upfile[]" size="30"/><a onclick="addrow();return false;" href="javascript:;">[+]</a></td></tr>
		</table>
		<div style="float:left;padding-left:24px;"><input type="submit" class="button" value=" 上 传 " /> </div>
	</form>
	
	<script type="text/javascript">parheight();</script>
	
	</body>
	</html>
EOF;
		return $s;
	}
}